package utils

import (
	"os"
	"time"
	"path"
	"fmt"
)

type CmdLog struct {
	dir string
	duration time.Duration
	file *os.File
	time time.Time
}

func NewCmdLogInstance(dir string, duration time.Duration) *CmdLog {
	instance := new(CmdLog)
	instance.dir = dir
	instance.duration = duration
	return instance
}

func (cl *CmdLog) Write(p []byte) (n int, err error) {
	if time.Since(cl.time) >= cl.duration {
		cl.time = time.Now()
		if nil != cl.file {
			cl.file.Close()
			cl.file = nil
		}
		name := fmt.Sprintf("%s.log", cl.time.Format("2006-01-02_15-04-05"))
		cl.file, err = os.Create(path.Join(cl.dir, name))
		if nil != err {
			return 0, err
		}
	}
	return cl.file.Write(p)
}
